<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
        v-if="$hasPerm('sys:dept:save')"
      >
        添加
      </el-button>
      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >
        导出表格
      </el-button>
    </div>

    <zk-table
      ref="ZKTableRef"
      index-text="#"
      :data="list"
      :columns="treeTable.columns"
      :stripe="treeTable.props.stripe"
      :border="treeTable.props.border"
      show-row-hover
      :show-index="treeTable.props.showIndex"
      is-fold
      :selection-type="treeTable.props.selectionType"
      :expand-type="treeTable.props.expandType"
      class="dept-content"
    >
      <template slot="level" slot-scope="{ row }">
        <el-tag :type="tagType[row.level - 1]">{{ row.level }}级</el-tag>
      </template>
      <template slot="manipulate" slot-scope="{ row }">
        <el-row>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleUpdate(row)"
            v-if="$hasPerm('sys:dept:update')"
          >修改</el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="handleDelete(row.id)"
             v-if="$hasPerm('sys:dept:delete')"
          >删除</el-button>
        </el-row>
      </template>
    </zk-table>

    <pagination
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      width="50%"
      @close="cleanFormData"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="form"
        label-position="left"
        label-width="85px"
        style="width: 80%; margin-left:50px;"
      >
        <el-form-item label="所属企业:" prop="companyId">
          <el-select v-model="form.companyId" placeholder="请选择所属企业">
            <el-option
              v-for="item in companyList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              style="width: 100%;"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门名称:" prop="name">
          <el-input v-model="form.name" placeholder="请输入部门名称" />
        </el-form-item>

        <el-form-item label="部门编码:" prop="code">
          <el-input v-model="form.code" />
        </el-form-item>
        <el-form-item label="部门类别:" prop="category">
          <el-input v-model="form.category" />
        </el-form-item>

        <el-form-item label="城市:" prop="city">
          <el-input v-model="form.city" />
        </el-form-item>
        <el-form-item label="负责人:" prop="managerId">
          <el-input v-model="form.managerId" />
        </el-form-item>
        <el-form-item label="父级部门:" prop="parentId">
          <!-- <el-cascader
            v-model="depts"
            :options="list"
            :props="deptOptions"
            :show-all-levels="false"
            clearable
            placeholder="请选择父级部门"
            @change="setDept"
          ></el-cascader> -->
          <el-cascader
           v-model="depts"
            :options="list"
            :props="deptOptions"
            clearable
            placeholder="请选择父级部门"
            style="width: 100%;"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="层级:" prop="level">
          <el-input v-model="form.level" />
        </el-form-item>
        <el-form-item label="备注:" prop="introduce">
          <el-input
            type="textarea"
            :maxlength="500"
            show-word-limit
            resize="none"
            v-model="form.introduce"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table
        :data="pvData"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  createDepartment,
  updateDepartment,
  deleteDepartment
} from "@/api/department";
import { fetchList as fetchCompanyList } from "@/api/company";
import waves from "@/directive/waves"; // waves directive
import { parseTime, cleanEmptyValue } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

export default {
  components: { Pagination },
  directives: { waves },

  data() {
    return {
      // 树形表格对象
      treeTable: {
        props: {
          stripe: true,
          border: true,
          showIndex: true,
          selectionType: false,
          expandType: false
        },
        columns: [
          {
            label: "部门名称",
            prop: "name"
          },
          {
            label: "负责人",
            prop: "managerId"
          },
          {
            label: "层级",
            type: "template",
            template: "level"
          },

          {
            label: "操作",
            type: "template",
            template: "manipulate"
          }
        ]
      },
      tagType: ["primary", "warning", "danger", "info"],
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10
      },

      showReviewer: false,
      form: {
        id: null,
        companyId: null,
        name: null,
        code: null,
        category: null,
        managerId: null,
        city: null,
        parentId: null,
        level: null,
        introduce: null
      },
      rules: {
        name: [{ required: true, message: "必填项", trigger: "blur" }],
        companyId: [{ required: true, message: "必填项", trigger: "blur" }],
        managerId: [{ required: true, message: "必填项", trigger: "blur" }],
        code: [{ required: true, message: "必填项", trigger: "blur" }],
        category: [{ required: true, message: "必填项", trigger: "blur" }],
        level: [{ required: true, message: "必填项", trigger: "blur" }]
      },

      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "修改",
        create: "添加"
      },
      companyList: [],
      depts: [],
      deptOptions: {
        value: "id",
        label: "name",
        expandTrigger: "hover",
        checkStrictly: true
      },
      dialogPvVisible: false,
      pvData: [],

      downloadLoading: false
    };
  },
  created() {
    this.getList();
    this.getCompanyList();
  },
  methods: {
    getList() {
      this.listLoading = true;

      fetchList(this.listQuery).then(response => {
        // console.log(response);
        this.list = response.page.list;
        this.total = response.page.totalCount;
        this.listLoading = false;
      });
    },

    handleFilter() {
      // this.getList();
    },

    getCompanyList() {
      fetchCompanyList({ page: 1, limit: 1000 }).then(resp => {
        this.companyList = resp.page.list;
      });
    },
    setDept1(v) {
      const len = v.length;
      if (len > 0) {
        this.form.parentId = v.pop();
        this.form.pids = v.join(",");
      } else {
        this.form.parentId = "0";
      }
    },
    setDept() {
      const len = this.depts.length;
      if (len > 0) {
        this.form.parentId = this.depts.pop();
        this.form.pids = this.depts.join(",");
      } else {
        this.form.parentId = "0";
      }
    },
    handleCreate() {
      // this.depts = []
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },

    createData() {
      // console.log(this.form);
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.setDept();
          cleanEmptyValue(this.form);
          createDepartment(this.form).then(() => {
            this.dialogFormVisible = false;
            this.getList();
          });
        }
      });
    },

    handleUpdate(row) {
      this.form = { ...row }; //
      this.depts = [];
      if (this.form.pids) {
        this.depts = this.form.pids.split(",");
      }
      if (this.form.parentId && this.form.parentId !== "0") {
        this.depts.push(this.form.parentId);
      }

      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.setDept();
          cleanEmptyValue(this.form);
          updateDepartment(this.form).then(() => {
            this.getList();
            this.dialogFormVisible = false;
          });
        }
      });
    },
    cleanFormData() {
      this.depts = [];
      this.form = {
        id: null,
        companyId: null,
        name: null,
        code: null,
        category: null,
        managerId: null,
        city: null,
        parentId: "0",
        level: null,
        introduce: null
      };
    },
    handleDelete(id) {
      this.$confirm("您确定要删除该记录吗?", "Warning", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteDepartment(id).then(() => {
            this.getList();
          });
        })
        .catch(msg => {
          console.log(msg);
        });
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData;
        this.dialogPvVisible = true;
      });
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = ["timestamp", "title", "type", "importance", "status"];
        const filterVal = [
          "timestamp",
          "title",
          "type",
          "importance",
          "status"
        ];
        const data = this.formatJson(filterVal);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "table-list"
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal) {
      return this.list.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? "ascending" : "descending";
    }
  }
};
</script>
<style scoped>
/deep/ .industry input::-webkit-input-placeholder {
  color: #717171 !important;
}
/deep/ .industry input::-moz-placeholder {
  /* Mozilla Firefox 19+ */
  color: #717171 !important;
}
/deep/ .industry input:-moz-placeholder {
  /* Mozilla Firefox 4 to 18 */
  color: #717171 !important;
}
/deep/ .industry input:-ms-input-placeholder {
  /* Internet Explorer 10-11 */
  color: #717171 !important;
}
</style>
